import { login, loginOut } from '@/apis/user'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo,removeUserInfo } from '@/utils/auth'
import { rsaEncrypt, rsaDecrypt } from '@/utils/rsa'
const state = {
	avatar: '',
	token: getToken(),
	userInfo: getUserInfo()
}
const mutations = {
	setToken(state, token) {
		state.token = token
		// 同步到缓存
		setToken(token)
	},
	removeToken(state) {
		// 删除Vuex的token
		state.token = null
		removeToken()
	},
	setUserInfo(state, userInfo) {
		state.userInfo = userInfo
		setUserInfo(JSON.stringify(userInfo))
	},
	removeUserInfo(state){
		state.userInfo = {};
		removeUserInfo();
	}
}
const actions = {
	// context上下文，传入参数
	async login({ commit }, data) {
		// console.log(data)
		// todo: 调用登录接口
		const res = await login({ ...data })
		if (res.code === 200) {
			// console.log('登录成功')
			const data1 = res.data;
			// console.log('data',data1)
			// console.log(1123123123132);
			commit('setToken', data1.token)
			commit('setUserInfo', data1)
			uni.switchTab({
				url: '/pages/index/index'
			})
		} else {
			console.log('登录失败')
			uni.utils.toast(res.message)
			// const timer = setTimeout(() => {
			//   uni.redirectTo({
			//     url: '/pages/login/index'
			//   })
			//   clearTimeout(timer)
			// }, 1500)

		}
		return res;
		// console.log(res)
		// 返回一个token 123456
	},
	// 退出登录
	async logOut(context) {
		// 删除token
		if (getToken()) {
			let res = await loginOut();
			if (res.code === 200) {
				uni.navigateTo({ url: '/pages/login/index' })
				context.commit('removeToken')
				context.commit('removeUserInfo');
			}
			return res;
		}else {
			uni.utils.toast('您还未登录呢');
		}
		// 删除用户信息
		// context.commit('setUserInfo', {})
	},
	async getInfo(context) {
		// const res = await getInfo(context.state.token)
		// console.log(res)
		// context.commit('setName', res.data.name)
		// context.commit('setAvatar', res.data.avatar)
	}
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}